package com.cskaoyan.controller.wx.zjh;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import com.cskaoyan.mapper.MarketStorageMapper;
import com.cskaoyan.module.bean.BaseRespVo;
import com.cskaoyan.module.pojo.MarketStorage;
import com.cskaoyan.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Date;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 *
 * @Description:
 * @Author: 周佳豪
 * @Date: 2022/04/11/19:04
 */
@RestController
public class WXFileUpload {
    @Autowired
    MarketStorageMapper StorageMapper;

    BaseRespVo baseRespVo = new BaseRespVo();

    @Value("${my.path}")
    String path;


    @PostMapping("wx/storage/upload")
    public BaseRespVo upload(@RequestParam("file") MultipartFile uploadFile, HttpServletRequest request) {
        String accessKeyId = "LTAI5tMegeHNWNhwLcJWUKQ8";
        String accessKeySecret = "i1NWpImPOePGok7EKYfY5Vn72SOUiK";
        String bucket = "project2file";
        String endPoint = "oss-cn-beijing.aliyuncs.com";
        String name = uploadFile.getOriginalFilename();
        String[] split = name.split("\\.");
        String oldName = "."+split[1];
        InputStream inputStream = null;
        try {
            inputStream = uploadFile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String newName = UUID.randomUUID().toString()+oldName;

        OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);

        PutObjectResult putObjectResult = ossClient.putObject(bucket, newName,inputStream);

        String saveName = "https://"+bucket+"."+endPoint+"/"+newName;

        MarketStorage marketStorage = new MarketStorage();
        marketStorage.setKey(newName);
        marketStorage.setName(oldName);
        String type = oldName.substring(oldName.lastIndexOf(".") + 1, oldName.length());
        marketStorage.setType("image/" + type);
        Integer size = (int) uploadFile.getSize();
        marketStorage.setSize(size);
        marketStorage.setUrl(saveName);
        marketStorage.setAddTime(new Date());
        marketStorage.setUpdateTime(new Date());
        marketStorage.setDeleted(false);
        int insert = StorageMapper.insert(marketStorage);
        if (insert == 1) {
            baseRespVo.setErrno(0);
            baseRespVo.setData(marketStorage);
            baseRespVo.setErrmsg("成功");
        }
        return baseRespVo;
    }
}
